package com.jet.core.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class RedisService<K, V> {

    private final RedisTemplate<K, V> redisTemplate;

    public RedisService(RedisTemplate<K, V> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public boolean hasKey(K key) {
        return Boolean.TRUE.equals(redisTemplate.hasKey(key));
    }

    public void set(K key, V value) {
        redisTemplate.opsForValue().set(key, value);
    }

    public void set(K key, V value, long timeout, TimeUnit timeUnit) {
        if (timeout > 0) {
            redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
        } else {
            set(key, value);
        }
    }

    public void setList(K key, List<V> list) {
        redisTemplate.opsForList().rightPushAll(key, list);
    }

    public V get(K key) {
        return redisTemplate.opsForValue().get(key);
    }

    public List<V> getList(K key) {
        return redisTemplate.opsForList().range(key, 0L, -1L);
    }

    public void delete(K key) {
        redisTemplate.delete(key);
    }

    public Long increment(K key, long delta) {
        return redisTemplate.opsForValue().increment(key, delta);
    }
}
